#pragma once

#include <iostream>
#include <unordered_map>
#include <functional>
#include <ctime>
#include <unistd.h>

using task_t = std::function<void()>;
static int number = 0;

void DownLoad()
{
    std::cout << "我是下载任务....." <<  getpid() << std::endl;
}

void Log()
{
    std::cout << "我是日志任务....." <<  getpid() << std::endl;
}

void Sql()
{
    std::cout << "我是数据库同步任务....." <<  getpid() << std::endl;
}

class Task
{
public:
    Task()
    {
        srand((unsigned int)time(nullptr));
        InserTask(DownLoad);
        InserTask(Log);
        InserTask(Sql);
    }
    // 插入任务
    void InserTask(task_t t)
    {
        tasks[number++] = t;
    }
    int SelectTask()
    {
        return rand() % number;
    }
    // 执行任务
    void Excute(int number)
    {
        if (tasks.find(number) == tasks.end())
            return;
        tasks[number]();
    }
    ~Task()
    {
    }

private:
    std::unordered_map<int, task_t> tasks;
};

Task ts;

void worker()
{
    while(true)
    {
        //写是四字节写，读也四字节读
        int cmd = 0;
        int n = ::read(0,&cmd,sizeof(cmd));
        if(n == sizeof(cmd))
        {
            ts.Excute(cmd);
        }
        else if(n == 0)
        {
            std::cout << "pid: " << getpid() << "quit..." << std::endl;
            break;
        }
        else
        {

        }
    }
}